import React from 'react'
import { Input, Button, message, Tag, Spin } from 'antd'
import marked from "marked"
// 高亮富文本
import hljs from 'highlight.js/lib/core';
import javascript from 'highlight.js/lib/languages/javascript'
import './index.scss'
import avatar from '@/assets/images/1.jpg'
import { getEmojiList } from '@/api/emoji'
import { submitComment, queryComment } from '@/api/index'
import { withRouter } from "react-router-dom"
import { articleDetail, addArticleReadCount, nextArticle } from '@/api/article'
import Store from '../../store/index'
import { HeartOutlined } from '@ant-design/icons'
import 'highlight.js/styles/atelier-sulphurpool-light.css'
import { jsPDF } from "jspdf"
import { createPdf } from '../../utils/index'
import moment from 'moment';

interface IProps{
  match?: any;
  history?: any;
}
interface IState{
   article:any,
  articleId: string,
  commentCotent: string,
  responsePerson: string, // 回复人·
  responsePersonId: string, // 回复人id
  commentList: any[],// 评论列表
  isLike: boolean, // 是否喜欢该文章
  emojiList: any[], // 表情列表
  emojiVisible: boolean, // 是否显示表情
  pageArticle: any[], // 前后一篇文章
  loading: boolean, // 是否加载
}
const doc = new jsPDF();
const { TextArea } = Input;
hljs.registerLanguage('javascript', javascript);
class Detail extends React.Component<IProps,IState> {
  contentRef: React.RefObject<any>;
  constructor(props) {
    super(props)
    this.contentRef = React.createRef()
    this.state = {
      article: {},
      articleId: '',
      commentCotent: '',
      responsePerson: '', // 回复人·
      responsePersonId: '', // 回复人id
      commentList: [],// 评论列表
      isLike: false, // 是否喜欢该文章
      emojiList: [], // 表情列表
      emojiVisible: false, // 是否显示表情
      pageArticle: [], // 前后一篇文章
      loading: false, // 是否加载
    }
  }
  UNSAFE_componentWillMount() {
    console.log(this)
    console.log(999)
  }
  async componentDidMount() {
    await hljs.initHighlightingOnLoad()
    console.log(this.props, 'hahahhahaha')
    await this.setState({ articleId: this.props.match.params.id })
    await this.getEmojiList()
    this.getArticleData()
    this.getNextArticle() // 拿下一篇文章
   
    //     doc.text("Hello world!", 10, 10);
    // doc.save("a4.pdf");
  }
  getArticleData = async () => {
    console.log('kaishiwenzhang1')
    this.setState({ loading: true })
    try {
      const res:any = await articleDetail({ articleId: this.state.articleId })
      if (res.code === 200) { // 切换文章成功
        await this.setState({ article: res.data })
        if (res.data) {
          console.log('ppp', this.props)
          this.markdownRender()
          this.addReadCount()
          this.queryComment()
        }

        this.setState({ loading: false })
        window.scrollTo(0, 0) // 切换文章后滚动到顶部
      } else {
        this.setState({ loading: false })
      }
    } catch (e) {
      console.log(e)
      this.setState({ loading: false })
    }

  }
  getNextArticle = async () => { // 获取前后篇文章
    const res:any = await nextArticle({
      articleId: this.state.articleId
    })
    if (res.code == 200) {
      this.setState({ pageArticle: res.data })
    }
  }
  changeArticle = async (name) => { // 切换文章
    if (name == 'pre' && this.state.pageArticle[0]) {
      await this.setState({ articleId: this.state.pageArticle[0].id })
      this.props.history.push({ pathname: '/article/detail/' + this.state.articleId })
      this.getArticleData()
      this.getNextArticle()
    } else if (name == 'next' && this.state.pageArticle[1]) {
      await this.setState({ articleId: this.state.pageArticle[1].id })
      this.props.history.push({ pathname: '/article/detail/' + this.state.articleId })
      this.getArticleData()
      this.getNextArticle()
    }
  }
  openEmoji = () => { // 打开表情列表
    this.setState(state => ({ emojiVisible: !state.emojiVisible }))

  }
  getEmojiList = async () => { // 获取表情
    const res:any = await getEmojiList({
      pageNum: 1,
      pageSize: 999
    })
    if (res.code === 200) {
      await this.setState({ emojiList: res.rows })
      console.log("表情拿到了")
    }
    return res
  }
  addReadCount = () => { // 添加阅读次数
    addArticleReadCount(
      parseInt(this.state.articleId)
    )
  }
  submitRemark = async () => { // 提交评论
    if (!Store.loginStatus) {
      message.error('请先登录！')
      return
    }
    if (this.state.commentCotent) {
      const res:any = await submitComment({
        content: this.state.commentCotent,
        userId: Store.userInfo.userId,
        userName: Store.userInfo.userName,
        articleId: this.state.articleId,
        responsePersonId: this.state.responsePersonId,
        responsePerson: this.state.responsePerson
      })
      if (res.code == 200) {
        message.success('评论成功！')
        this.setState({ commentCotent: '' })
        this.setState({ responsePerson: '', responsePersonId: '' })
        this.queryComment()
      } else {
        message.error('评论失败！！！')
      }
    } else {
      message.error('请输入评论内容！')
    }

    console.log(444)
  }
  queryComment = async () => { // 查询评论
    const res:any = await queryComment(this.state.articleId)
    if (res.code == 200) {
      console.log("当前的表情.",this.state.emojiList)
      await this.setState({ commentList: res.list })
      this.forceUpdate() // 重新渲染 更新评论中的表情
      console.log(res)
    }
  }
  commentChange = (e) => {
    this.setState({ commentCotent: e.target.value })
    console.log(e.target.value)
  }
  selectEmoji = (emoji) => { // 选择表情
    console.log(emoji)
    this.setState({
      emojiVisible: false
    })
    let commentCotent = this.state.commentCotent
    commentCotent += emoji.name
    this.setState({ commentCotent })
  }
  async markdownRender() {
    marked.setOptions({
      renderer: new marked.Renderer(),
      gfm: true,
      tables: true,
      breaks: false,
      pedantic: false,
      sanitize: false,
      smartLists: true,
      smartypants: false,
      highlight: function (code) {
        return hljs.highlightAuto(code).value;
      }
    });
    // await this.setState({ article: { ...this.state.article, content: this.state.article.content } })
    let blocks = document.querySelectorAll('code');
    blocks.forEach(block => {
      hljs.highlightBlock(block)
    })
    document.getElementById('markdown-content')!.innerHTML = marked(this.state.article.content).replace(/<pre>/g, "<pre class='hljs'>")
  }
  handleClose() { //关闭回复标签
    this.setState({ responsePerson: '', responsePersonId: '' })
  }
  response(item) { //回复
    console.log(item)
    this.setState({
      responsePerson: item.nickName,
      responsePersonId: item.userId
    }, () => {
      console.log(this.state.responsePerson)
    })
  }
  checkEmojiInclude = (content, index) => { // 检测评论内容是否含有表情
    const reg = /\[([\u4e00-\u9fa5]|\w)+\]/g

    let div = document.getElementById('commentContent' + index)
    if (div) {
      console.log(div.innerHTML.match(reg))
      const arr = div.innerHTML.match(reg) // 匹配表情返回一个数组
      let urls = []

      div.innerHTML = div.innerHTML.replace(reg, (value) => {
        console.log('执行了多少次', arr)
        let url = 'http://heyuanjie.top/emoji/emoji.png'
        this.state.emojiList.forEach((emoji) => {
          if (emoji.name == value) {
            url = emoji.url
          }
        })
        return `<img src='${url}' alt="emoji" style="width:20px;margin-right:2px"/>`


      })
    }

    return content
  }
  likeArticle = () => {
    this.setState({ isLike: true })
  }
  render() {
    return (
      <Spin tip="Loading..." spinning={this.state.loading}>
        <div className='deatil-box'>
          {this.state.article ?
            <div className='detail'>
              <h1 className='title'>{this.state.article.title}</h1>
              <div className='status flex align-center'>
                {/* <span>{{ detail.month }} {{ detail.day }}, {{ detail.year }}</span> */}
                <span>阅读：{this.state.article.readCount}</span>
                <span>字数：{this.state.article.wordCound}</span>
                <span>评论：{this.state.article.remarkCount}</span>
                <span>喜欢: {this.state.article.likeCount}</span><HeartOutlined style={this.state.isLike ? { color: 'red' } : {}} onClick={this.likeArticle} />
                {
                  this.state.article.updateTime ? <span>更新：<span className='time'>{moment(this.state.article.updateTime).format('YYYY-MM-DD')}</span></span> :
                    <span>日期：<span className='time'>{moment(this.state.article.createTime).format('YYYY-MM-DD')}</span></span>
                }

              </div>
              <div className='content markdown-body'>
                {/* <div ref={this.contentRef}>
                        </div> */}
                <div id='markdown-content'></div>
                {/* <div dangerouslySetInnerHTML={{ __html: this.state.article.content }} /> */}
              </div>
              <div id='hash'></div>
              {/* <div>
            <Button onClick={()=>{
              console.log("333")
             let img= createPdf('markdown-content')
             console.log(img,'8888888888')
             this.setState({img})
            }
              }>下载PDF文档</Button>
          </div> */}
              <div className='page-box'>
                <div className='pre-page' onClick={() => { this.changeArticle('pre') }} style={!this.state.pageArticle[0] ? { color: '#999' } : {}}>
                  <span>&lt; 上一篇</span>
              &nbsp;
              <span className='article-title'>
                    {this.state.pageArticle[0] ? this.state.pageArticle[0].title : '到头了。。。'}
                  </span>
                </div>
                <div className='next-page' onClick={() => { this.changeArticle('next') }} style={!this.state.pageArticle[1] ? { color: '#999' } : {}}>
                  <span className='article-title'>
                    {this.state.pageArticle[1] ? this.state.pageArticle[1].title : '到底了。。。'}
                  </span>
              &nbsp;
              <span>下一篇 &gt;</span>

                </div>
              </div>
              <div className='remark'>
                {this.state.responsePerson && (<Tag color="geekblue" closable onClose={() => this.handleClose()}>@{this.state.responsePerson}</Tag>)}
                <TextArea placeholder='随便写点吧' allowClear value={this.state.commentCotent} onChange={this.commentChange} />
                <div className='remark-bar'>
                  <div className='emoji'>
                    <img src='http://heyuanjie.top/emoji/emoji.png' alt="emoji" onClick={this.openEmoji} />
                    <div className='emoji-list-box' style={!this.state.emojiVisible ? { display: 'none' } : {}}>
                      {
                        this.state.emojiList.map((item, index) => {
                          return (
                            <div key={index} className='emoji-item'>
                              <img src={item.url} alt="emoji" onClick={() => { this.selectEmoji(item) }} />
                            </div>
                          )
                        })
                      }

                    </div>
                  </div>

                  <Button onClick={this.submitRemark}>评论</Button>
                </div>
              </div>
              <div className='comment'>
                <p><span>评论列表</span><span>(999)</span></p>
                {
                  this.state.commentList.map((item, index) => {
                    return (
                      !item.responsePersonId ? <div className='comment-list' key={item.id}>
                        <div className='comment-person'>
                          <div className='left'>
                            <div className='avatar'>
                              <img src={item.avatar} alt='' width='40px' height='40px' />
                            </div>
                            <div className='name'>
                              {item.nickName}
                            </div>
                          </div>
                          <div className='right'>
                            <div className='response' onClick={() => this.response(item)}>
                              回复
                        </div>
                            <div className='time'>
                              {item.createTime}
                            </div>
                          </div>

                        </div>
                        <div className='commentContent' id={'commentContent' + index}>{
                          this.checkEmojiInclude(item.content, index)
                        }</div>
                      </div>
                        :
                        <div className='comment-list' key={item.id} style={{ marginLeft: '24px' }}>
                          <div className='comment-person'>
                            <div className='left'>
                              <div className='avatar'>
                                <img src={avatar} alt='' width='40px' height='40px' />
                              </div>
                              <div className='name'>
                                <span>{item.userName}</span>

                                <span></span>
                                <span className='responsePerson'>
                                  @{item.responsePerson}
                                </span>

                              </div>
                            </div>
                            <div className='right'>
                              <div className='response' onClick={() => this.response(item)}>
                                回复
                          </div>
                              <div className='time'>
                                {item.createTime}
                              </div>
                            </div>
                          </div>

                          <div className='commentContent' id={'commentContent' + index}>{this.checkEmojiInclude(item.content, index)}</div>
                        </div>
                    )
                  })
                }
              </div>
            </div>
            :
            <div>该文章已经不再了。。。</div>
          }
        </div>
      </Spin>
    )
  }
}
export default withRouter(Detail)
